import { VNode, reactive, h, defineComponent } from 'vue'
import type { LoadingProps } from './typing'

import Loading from './Loading.vue'
import { createBlock, createVNode, openBlock } from '@vue/runtime-core'
// TODO 先放一放
export function createLoading(props?: Partial<LoadingProps>, target?: HTMLElement, wait = false) {
  let vm: Nullable<VNode> | any = null
  const data = reactive({
    tip: '',
    loading: true,
    ...props,
  })
  const render = (arg) => {
    return openBlock(), createBlock('div', null, arg)
  }
  const LoadingWrap = defineComponent({
    render() {
      return h(Loading, { ...data } as any)
    },
  })
  vm = createVNode(LoadingWrap)
  if (wait) {
    // TODO fix https://github.com/anncwb/vue-vben-admin/issues/438
    setTimeout(() => {
      render(vm)
    }, 0)
  } else {
    render(vm)
  }
  function close() {
    if (vm?.context?.$el && vm?.context?.$el?.$parent) {
      // vm?.context?.$parent.parentElement.removeChild(vm.context.wrapEl)
    }
  }

  function open(target: HTMLElement = document.body) {
    // console.log('open------', vm, target)
    // if (!vm || !vm.context || !vm.context.$el) {
    //   return
    // }
    // target.appendChild(vm as HTMLElement)
  }

  if (target) {
    open(target)
  }
  return {
    vm,
    close,
    open,
    setTip: (tip: string) => {
      data.tip = tip
    },
    setLoading: (loading: boolean) => {
      data.loading = loading
    },
    get loading() {
      return data.loading
    },
    get $el() {
      return vm?.el as HTMLElement
    },
  }
}
